const axios = require('axios');
const crypto = require('crypto');

/**
 * 权益核销服务
 */
class EquityService {
  /**
   * 构造函数
   * @param {String} config.baseUrl 基础URL
   * @param {String} config.channelCode 渠道编码
   * @param {String} config.privateKey 签名密钥
   */
  constructor() {
    this.config = {
      baseUrl: 'https://qy.cmicvip.cn',
      apiPath: '/cmpp-api/external/commonBusinessOpenCallback',
      channelCode: '12646114',
      privateKey: 'FOCU8T7nWLftpvHW'
    };
  }

  /**
   * 推送权益核销状态
   * @param {Object} params 请求参数
   * @returns {Promise} 返回请求结果
   */
  async pushEquityStatus(params) {
    // 构造请求头
    const now = new Date();
    const reqTime = this.formatDate(now, 'yyyyMMddHHmmssSSS');
    const transactionId = this.generateTransactionId();
    
    const header = {
      apiId: '200044',
      channelCode: this.config.channelCode,
      transactionId,
      reqTime,
      version: '1.0'
    };

    // 生成签名
    const signStr = transactionId + reqTime + this.config.privateKey + JSON.stringify(params);
    header.sign = this.generateMd5(signStr).toUpperCase();

    // 构造请求体
    const requestBody = {
      contractRoot: {
        head: header,
        body: params
      }
    };

    // 发送请求
    try {
      const response = await axios.post(
        `${this.config.baseUrl}${this.config.apiPath}`,
        requestBody,
        {
          headers: {
            'Content-Type': 'application/json',
            'Connection': 'keep-alive'
          }
        }
      );
      
      return response.data;
    } catch (error) {
      console.error('推送权益核销状态失败:', error);
      throw error;
    }
  }

  /**
   * 生成MD5签名
   * @param {String} str 原始字符串
   * @returns {String} MD5签名
   */
  generateMd5(str) {
    return crypto.createHash('md5').update(str).digest('hex');
  }

  /**
   * 生成交易流水号
   * @returns {String} 交易流水号
   */
  generateTransactionId() {
    return Date.now().toString() + Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  }

  /**
   * 格式化日期
   * @param {Date} date 日期对象
   * @param {String} format 格式字符串
   * @returns {String} 格式化后的日期字符串
   */
  formatDate(date, format) {
    const pad = num => num.toString().padStart(2, '0');
    const map = {
      yyyy: date.getFullYear(),
      MM: pad(date.getMonth() + 1),
      dd: pad(date.getDate()),
      HH: pad(date.getHours()),
      mm: pad(date.getMinutes()),
      ss: pad(date.getSeconds()),
      SSS: pad(date.getMilliseconds(), 3)
    };
    
    return format.replace(/(yyyy|MM|dd|HH|mm|ss|SSS)/g, matched => map[matched]);
  }
}

module.exports = EquityService;